<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
class CatField extends \app\admin\controller\Admin{
    public function __construct(\think\App $app) {
        parent::__construct($app);
        $this->model=new \app\admin\model\CatFieldModel();
        $this->validate=new \app\admin\validate\CatFieldValidate();
       //字段类型
       $this->fieldtype_inc=array(
           "varchar"=>              "字符型0-255字节(varchar)",
           "char"=>                 "定长字符型0-255字节(char)",
           "text"=>                 "小型字符型(text)",
           "mediumtext"=>           "中型字符型(mediumtext)",
           "longtext"=>             "大型字符型(longtext)",
           "tinyint"=>              "小数值型(tinyint)",
           "smallint"=>             "中数值型(smallint)",
           "int"=>                  "大数值型(int)",
           "bigint"=>               "超大数值型(bigint)",
           "float"=>                "数值浮点型(float)",
           "double"=>               "数值双精度型(double)",
           "date"=>                 "日期型(date)",
           "datetime"=>             "日期时间型(datetime)",
       );
       View::assign("fieldtype_inc",$this->fieldtype_inc);
       //表单类型
       $this->formtype_inc=array(
           "text"=>              "单行文本框(text)",
           "password"=>          "密码框(password)",
           "select"=>            "下拉框(select)",
           "selects"=>           "多选下拉(selects)",           
           "radio"=>             "单选框(radio)",
           "checkbox"=>          "复选框(checkbox)",
           "textarea"=>          "多行文本框(textarea)",
           "tiny"=>              "推荐编辑器(tiny)",
           "editor"=>            "编辑器(editor)",
           "image"=>             "图片(image)",
           "morepic"=>           "多图上传(morepic)",
           "morevalue"=>         "多值字段(morevalue)",
           "file"=>              "文件(file)",
           "video"=>             "视频(video)",
           "date"=>              "日期(date)",
           "baidumap"=>          "百度地图(map)",
       );  
       View::assign("formtype_inc",$this->formtype_inc);
       //常用正则
       $this->pattern_inc=array(
           "/^[0-9.-]+$/"=>                             "数字",
           "/^[0-9-]+$/"=>                              "整数",
           "/^[1-9]\d*$/"=>                             "大于0",
           "/^[a-z]+$/i"=>                              "字母",
           "/^[0-9a-z]+$/i"=>                           "数字+字母",
           "/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/"=>          "E-mail",
           "/^[0-9]{5,20}$/"=>                          "QQ",
           "/^http:\/\//"=>                             "超级链接",
           "/^(1)[0-9]{10}$/"=>                         "手机号码",
           "/^[0-9-]{6,13}$/"=>                         "电话号码",
       );        
       View::assign("pattern_inc",$this->pattern_inc);
       //系统字段（禁止删除）
       $this->systemfield_inc=array("name","classpath","thumb","lencord","listtemp","viewtemp","status","pagetitle","keywords","description");
       View::assign("systemfield_inc",$this->systemfield_inc);
    }    
    public function index(){
        $data=$this->model->order('sort asc,field_id asc')->select();
        View::assign("data",$data);
        return View::fetch();        
    }
    //更新排序
    public function updateSort(){
        $field_id=Request::param('field_id');
        $sort=Request::param('sort');
        foreach($field_id as $key=>$v){
            $this->model->update(['field_id'=>$field_id[$key],'sort'=>$sort[$key]]);
        }
        $this->success("设置成功");
    }       
    public function add(){
        if(request()->isPost()){
            $data=$this->request->param();
            if(!$this->validate->check($data)){
                $this->error($this->validate->getError());
            }
            //完整表名获取 判断主表 还是副表
            $table_name = $this->model->getTbName($data['issystem']);  
            //验证字段在数据表里是否存在了
            if($this->model->field_exists($table_name,$data['field'])){
                $this->error("该字段在数据表已存在");
            }
            //增加字段
            $field = array(
                'tablename' => config('database.connections.mysql.prefix'). $table_name,
                'fieldname' => $data['field'],
                'fieldlen' => $data['fieldlen'],
                'defaultval' => $data['defaultval'],
            );  
            $this->model->addFieldSql($data['fieldtype'],$field);
            $savefun_trigger=implode("|",$data['savefun_trigger']);
            if($savefun_trigger){
                $data['savefun_trigger']="|".$savefun_trigger."|";
            }            
            $data['htmlcode']=$this->model->createFieldHtmlCode($data);
            //如果是morevalue需要对defaultvalue进行加工
            if($data["formtype"]=="morevalue"){
                $data["defaultval"]=$this->model->detailMorevalueDefaultval($data);
            }              
            $this->model->save($data);
            $lastId=$this->model->field_id;
            $this->UserLogModel->add(Request()->action(),$this->model->getName(),$lastId,$this->request->param());
            $this->success("添加成功");
        }else{          
            return View::fetch();
        }
    }
    public function update(){
        if(request()->isPost()){
            $data=$this->request->param();
            if(!$this->validate->check($data)){
                $this->error($this->validate->getError());
            }
            //增加field_id字段校验
            $this->validate->append('field_id','require');
            $r=$this->model->find($data['field_id']);
            if(!$r){
                $this->error("字段信息不存在");
            }
            //完整表名获取 判断主表 还是副表
            $table_name = $this->model->getTbName($r['issystem']);
            if ($data['field'] != $r['field']&& $this->model->field_exists($table_name, $data['field'])) {
                $this->error("该字段在数据表已存在");
            }
            $field = array(
                'tablename' => config('database.connections.mysql.prefix'). $table_name,
                'newfieldname' => $data['field'],
                'oldfieldname' => $r['field'],
                'fieldlen' => $data['fieldlen'],
                'defaultval' => $data['defaultval'],
            );            
            $this->model->editFieldSql($data['fieldtype'],$field);
            //更新htmlcode
            $data['htmlcode']=$this->model->createFieldHtmlCode($data);
            //如果是morevalue需要对defaultvalue进行加工
            if($data["formtype"]=="morevalue"){
                $data["defaultval"]=$this->model->detailMorevalueDefaultval($data);
            }              
            $data['savefun_trigger']=implode("|",$data['savefun_trigger']);
            if($data['savefun_trigger']){
                $data['savefun_trigger']="|".$data['savefun_trigger']."|";
            } 
            $this->model->update($data);
            //更新栏目模型
            $model=Db::name("model")->where([["cat_is_enter","like","%".$data['field']."%"]])->select();
            $ModelModel=new \app\admin\model\ModelModel();
            foreach($model as $v){
                $ModelModel->updateCatModelTemp($v);
            }          
            //
            $this->UserLogModel->add(Request()->action(),$this->model->getName(),$r['field_id'],$this->request->param());
            $this->success("修改成功");
        }else{
            $field_id=Request::param("field_id");
            $r=$this->model->find($field_id);
            View::assign("r",$r);
            return View::fetch();
        }
    }
    //删除
    public function delete(){
        $field_id=Request::param('field_id',0,"intval");
        $r=$this->model->find($field_id);
        if(!$r){$this->error("数据不存在");}
        //完整表名获取 判断主表 还是副表
        $table_name = $this->model->getTbName($r['issystem']);
        //判断是否允许删除
        if (in_array($r['field'],$this->systemfield_inc)){
            $this->error("系统字段不允许被删除!");
        }
        $this->model->deleteFieldSql($r['field'], $table_name);
        $this->model->where("field_id",$field_id)->delete();
        $this->UserLogModel->add(Request()->action(),$this->model->getName(),$field_id,$this->request->param());
        $this->success("删除成功");
    }
}